<?php

namespace app\modules\backend\controllers;

use Yii;
use app\tools\Re;
use app\tools\Tool;
use app\models\Admin;
use app\models\Identity;
use app\models\AuthItemChild;
use app\models\AuthAssignment;
use app\models\UserLogin;
use app\filters\auth\HttpBearerAuth;

class UserController extends BaseController
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        if (Yii::$app->getRequest()->getMethod() !== 'OPTIONS') {
            $behaviors['authenticator'] = [
                'class' => HttpBearerAuth::class,
                'optional' => [
                    'login',
                ],
            ];
        }
        return $behaviors;
    }

    /**
     * 登录接口(账号密码)
     */
    public function actionLogin(){
        $username = Yii::$app->request->post('userName', '');
        $password = Yii::$app->request->post('password', '');
        if (empty($username) || empty($password)) {
          return Re::data(null, '参数错误', Re::ERROR);
        }
        $user = Identity::findOne(['username'=>$username, 'status'=> 1]);
        if($user && Yii::$app->security->validatePassword($password, $user->password)){
            Yii::$app->user->login($user); // 这句不能丢，用户登录就，才能自动补全ar行为中的user_id
            $token = UserLogin::generateToken();
            return Re::data([
                'Authorization'=>'Bearer '.$token,
                'id' => $user->id,
                'username' => $user->username,
                'icon' => $user->icon,
                'first_access' => AuthItemChild::getFirstPermission($user->id)->child,
                'role' => AuthItemChild::getFirstPermission($user->id)->parent,
            ]);
        }else{
            return Re::data(null, '账号名或密码错误', Re::ERROR);
        }
    }

    /**
     * 后台用户列表
     */
    public function actionManagerList(){
        $status = Yii::$app->request->post('status', '-2');
        $role_name = Yii::$app->request->post('role', '-1');
        $name = Yii::$app->request->post('name', '');
        $username = Yii::$app->request->post('username', '');
        $page = Yii::$app->request->post('page', 0);
        $user_admin = Admin::findOne(Yii::$app->user->id);
        //$bid = $user_admin->bid;
        $user_query = Admin::find()
          ->leftJoin("auth_assignment", "auth_assignment.user_id = admin.id")
          ->where(['admin.status' => [0,1]])
          ->andWhere("id <> $user_admin->id");
        if ($status > -1) {
            $user_query->andWhere(['status' => $status]);
        }
        if ($role_name) {
          $user_query->andWhere(['item_name' => $role_name]);
        }
        if (!empty($name)) {
            $user_query->andWhere(['like', 'name', $name]);
        }
        if (!empty($username)) {
            $user_query->andWhere(['like', 'username', $username]);
        }
        $user_list = $user_query->limit(Admin::PAGE_SIZE)->offset($page*Admin::PAGE_SIZE)->all();
        $user_data = [];
        if ($user_list) {
          foreach ($user_list as $v) {
            $auth_assignment = AuthAssignment::find()->where(['user_id' => $v->id])->one();
            $user_data[] = [
              'id' => $v->id,
              'shop_id' => $v->shop_id,
              'shop_name' => $v->shop_id ? $v->shop->name : '',
              'name' => $v->name,
              'username' => $v->username,
              'icon' => $v->icon,
              'role' => $auth_assignment ? $auth_assignment->item_name : '',
              'status' => $v->status,
              'created_time' => date("Y-m-d H:i", $v->created_at),
            ];
          }
        }
        return Re::data([
            'data' => $user_data,
            'totalPage' => $user_query->count(),
            'currentPage' => $page,
            'perPage' => Admin::PAGE_SIZE
        ]);
    }

    public function actionAdminListForSelect(){
      $user_list = Admin::find()->where(['status' => 1])->andWhere("username <> 'admin'")->all();
      return Re::data(['data' => $user_list]);
    }

    /**
     * 后台用户创建/编辑
     */
    public function actionEditUser(){
        $id = Yii::$app->request->post('id', 0);
        $post = Yii::$app->request->post();
        $keys = array_keys($post);
            $first_key = $keys[0];
            if (!$first_key) {
            return;
        }
        $user_admin = Admin::findOne(Yii::$app->user->id);
        if(isset($post['password']) && $post['password']){
            $post['password'] = Yii::$app->security->generatePasswordHash($post['password']);
        }
        $query = Admin::find()->where(['username' => $post['username']]);
        if($id){
            $query->andWhere('id != :id', [':id'=>$id]);
        }
        if($query->exists()){
            return Re::data(null, '该账号已被使用', Re::ERROR);
        }
        if($id){
            $model = Admin::findOne($id);
            if(!$model){
                return Re::data(null, '您修改的数据不存在', Re::ERROR);
            }
        }else{
            $model = new Admin();
        }
        $model->load($post, '');
        if($model->save()){
            if($model->username != 'admin' && isset($post['role']) && $post['role']){
                Yii::$app->authManager->revokeAll($model->id);
                Yii::$app->authManager->assign(
                    Yii::$app->authManager->getRole($post['role']), $model->id);
            }
            if(isset($post['password'])){
                $model->removeTokens();
            }
            return Re::data();
        }else{
            return Re::data(null, $model->showErrors(), Re::ERROR);
        }
    }

    /**
     * 后台用户状态修改
     */
    public function actionChangeUserStatus(){
        $id = Yii::$app->request->post('id', 0);
        $status = Yii::$app->request->post('status', 0);
        $user = Admin::findOne($id);
        if (empty($user)) {
            return Re::data(null, '信息读取失败', Re::ERROR);
        }
        $user->status = $status;
        if (!$user->save()) {
            return Re::data(null, '操作失败', Re::ERROR);
        }
        return Re::data();
    }

    //后台相关人员列表
    public function actionAdminUserForSelect(){
      $role = Yii::$app->request->post('role', '');
      $user_list = Admin::find()
        ->leftJoin("auth_assignment", "auth_assignment.user_id = admin.id")
        ->where(['admin.status' => 1, 'item_name' => $role])
        ->select("id, name")
        ->all();
      return Re::data(['data' => $user_list]);
    }
}
